import { useMemo, useRef, useEffect, useState, useLayoutEffect } from 'react';
import { createPortal } from 'react-dom';

import "./index.less";
import { Button, Col, Form, Input, Popover, Row } from "antd";
import { useFocused, useSlate } from "slate-react";
import { Transforms } from "slate";

const RenderContent=({url,onClose,parentCurrent,open})=>{
  const [isForm,setIsForm]=useState();
  const [form]=Form.useForm();
  const editor: any = useSlate();
  const ref=useRef();
  const onRemove=()=>{
    editor.unwrapLink();
  }
  const onUpdate=()=>{
    setIsForm(true)
  }
  const onFinish=(values)=>{
    onClose()
    setIsForm(false)
    editor.updateLink(values?.url)
  }

  useEffect(()=>{
    if(!open){
      setIsForm(false)
    }                                 
},[open])

  const style=useMemo(()=>{
    const el=parentCurrent?.()
    if(!el){
      return{}
    }
    const rect=el.getBoundingClientRect()
    return {
      display:'block',
      transform:`translate3d(${rect?.x}px,${rect?.y+rect?.height+10}px,0)`
    }
  },[open])

  const onDocumentClick = (event:MouseEvent) => {
    const current_node = event.target;
    const $modal = ref.current;
    console.log($modal?.contains(current_node),current_node)
    if (!$modal?.contains(current_node)) {
    
      onClose?.()

    }
  };


  useLayoutEffect(() => {
    let timer:any=null;

    if(open){
      timer=setTimeout(()=>{
        document.addEventListener("click", onDocumentClick);
      },200)
    }else{
      document.removeEventListener("click", onDocumentClick);
   }
    return () => {
      if(timer){
        clearTimeout(timer)
      }
     
      document.removeEventListener("click", onDocumentClick);
    };
  }, [open,isForm]);

  if(!open){
   return null
  }

 return (<div ref={ref} style={style}  className="editor-link-tools"  contentEditable={false} >
   {isForm?(<Form
      onFinish={onFinish}
      labelCol={{ span: 6 }}
      form={form}
    >
  <Row>
     <Col span={18}>
      <Form.Item
        label="链接"
        name="url"
        rules={[{ required: true }, { type: "url" }]}
      >
        <Input></Input>
      </Form.Item>
      </Col>
      <Col span={5} offset={1}>
      <Form.Item>
        <Button type="primary" htmlType="submit">确认</Button>
      </Form.Item>
      </Col>
      </Row>
    </Form>):( <div className='tools-content'>
 <span className="tools-link">{url}</span>
  <div>
    <Button onClick={onUpdate}>修改</Button>
    <Button onClick={onRemove}>删除</Button>
  </div>
 </div>)}

 </div>)

}

export default ({ attributes, children, element }: any) => {
  const ref = useRef<any>();
  const url = element?.url;
  const editor : any = useSlate();
  const  {emit,focus,...reset}=editor
 const [open,setOpen]=useState();
  const InlineChromiumBugfix = () => (
    <span contentEditable={false} style={{ fontSize: 0 }}>
      {String.fromCodePoint(160)}
    </span>
  );



 const onClick=(event)=>{
    event.preventDefault()
    setTimeout(() => {
      window.open(url, "_blank");
   });
 }
 const onMouseOver=()=>{
  setOpen(true)
 }
//  const onMouseLeave=()=>{
//   setOpen(false)
//  }
 const onClose=()=>{
  setOpen(false)
 }
 

  return (
    <span  {...attributes}   
    onMouseOver={onMouseOver}
 >
         {
          createPortal(
            <RenderContent parentCurrent={()=>{
               return ref.current
            }}  onClose={onClose} open={open} url={url}/>,
            document.body
          )
         } 
        <a
          ref={ref}
          className="element-link"
          href={url}
       
       //   onClick={onClick}
          target="_blank"
        >
          <InlineChromiumBugfix />
          {children}
          <InlineChromiumBugfix />
        </a>
      
    </span>
  );
};

